﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Collections.Specialized;
using System.Net.Cache;

namespace _180FrameWork.Common
{
    public class WebRequestHelper : BaseWebClientHelper
    {
        public WebRequestHelper()
        {

        }

        #region post

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="strBody">请求参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, string strBody, IDictionary<string, string> headerparameters = null)
        {
            HttpWebRequest req = GetWebRequest(url, "POST", headerparameters);
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            if (strBody != null)
            {
                byte[] postData = Encoding.UTF8.GetBytes(strBody);
                System.IO.Stream reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                reqStream.Close();
            }
            else
            {
                req.ContentLength = 0;
            }
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }
        /// <summary>
        /// 执行HTTP POST请求。（JSON格式）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="strBody"></param>
        /// <param name="headerparameters"></param>
        /// <returns></returns>
        public string DoPostJson(string url, string strBody, IDictionary<string, string> headerparameters = null)
        {
            HttpWebRequest req = GetWebRequest(url, "POST", headerparameters);
            req.ContentType = "application/json;charset=utf-8";

            if (strBody != null)
            {
                byte[] postData = Encoding.UTF8.GetBytes(strBody);
                req.GetRequestStream().Write(postData, 0, postData.Length);
                req.GetRequestStream().Close();
            }
            else
            {
                req.ContentLength = 0;
            }
            HttpWebResponse rsp;
            try
            {
                rsp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException e)
            {
                rsp = (HttpWebResponse)e.Response;
            }
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = Encoding.UTF8;
            return GetResponseAsString(rsp, encoding);
        }
        /// <summary>
        /// 执行HTTP POST请求。（XML格式）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="strBody"></param>
        /// <param name="headerparameters"></param>
        /// <returns></returns>
        public string DoPostXml(string url, string strBody, IDictionary<string, string> headerparameters = null)
        {
            HttpWebRequest req = GetWebRequest(url, "POST", headerparameters);
            req.ContentType = "application/xml;charset=utf-8";

            if (strBody != null)
            {
                byte[] postData = Encoding.UTF8.GetBytes(strBody);
                req.GetRequestStream().Write(postData, 0, postData.Length);
                req.GetRequestStream().Close();
            }

            HttpWebResponse rsp;
            try
            {
                rsp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException e)
            {
                rsp = (HttpWebResponse)e.Response;
            }
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = Encoding.UTF8;
            return GetResponseAsString(rsp, encoding);
        }
        /// <summary>
        /// 执行HTTP POST请求。（文件格式）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fs"></param>
        /// <param name="filename"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public string DoPostFile(string url, byte[] fs, string filename, IDictionary<string, string> parameters = null)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            req.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream rs = req.GetRequestStream();

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            if (parameters != null)
            {
                foreach (string key in parameters.Keys)
                {
                    rs.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem = string.Format(formdataTemplate, key, parameters[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    rs.Write(formitembytes, 0, formitembytes.Length);
                }
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
            string header = string.Format(headerTemplate, "file", filename);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            rs.Write(fs, 0, fs.Length);

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            //获取到上传请求的响应
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            string encodingName = "";
            if (rsp.CharacterSet != null)
                encodingName = rsp.CharacterSet;
            else
                encodingName = "utf-8";
            Encoding encoding = Encoding.GetEncoding(encodingName);
            return GetResponseAsString(rsp, encoding);
        }

        #endregion

        #region get

        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="headerparameters">请求头部参数</param>
        /// <returns>HTTP响应</returns>
        public string DoGet(string url, IDictionary<string, string> parameters = null, IDictionary<string, string> headerparameters = null)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQueryIDictionary(parameters);
                }
                else
                {
                    url = url + "?" + BuildQueryIDictionary(parameters);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "GET", headerparameters);
            req.ContentType = "text/html;charset=utf-8";

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = Encoding.UTF8;
            return GetResponseAsString(rsp, encoding);
        }
        /// <summary>
        /// 执行HTTP GET请求。（文件格式）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="headerparameters"></param>
        /// <returns></returns>
        public Stream DoGetFile(string url, IDictionary<string, string> parameters = null, IDictionary<string, string> headerparameters = null)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQueryIDictionary(parameters);
                }
                else
                {
                    url = url + "?" + BuildQueryIDictionary(parameters);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "GET", headerparameters);
            req.ContentType = "text/html;charset=utf-8";

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = Encoding.UTF8;
            return GetResponseAsStream(rsp, encoding);
        }
        /// <summary>
        /// 执行HTTP GET请求。（分片文件格式）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="parameters"></param>
        /// <param name="headerparameters"></param>
        /// <returns></returns>
        public Stream DoGetFile(string url, long from, long to, IDictionary<string, string> parameters = null, IDictionary<string, string> headerparameters = null)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQueryIDictionary(parameters);
                }
                else
                {
                    url = url + "?" + BuildQueryIDictionary(parameters);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "GET", headerparameters);
            req.ContentType = "text/html;charset=utf-8";
            req.AddRange(from, to);


            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = Encoding.UTF8;
            return GetResponseAsStream(rsp, encoding);
        }

        #endregion
    }
}
